一个例子说明promise基本用法

2019-07-02 17:05:44 浏览数 (1)

代码语言:javascript复制
 function a(something) {
      return new Promise((resolve, reject) => {
        if (something) {
          const sucessObjet = {
            msg: 'Success',
            data: 'some data'
          }

          throw new Error('Failure!')

          resolve(sucessObjet);

        } else {
          const errorOjbect = {
            msg: 'An error occoured',
            data: 'some wrong data'
          };
          reject(errorOjbect)
        }
      })
    }

    a(false).then(
      result => {
        console.log('false result', result);
      },
      e => {
        console.log('false e', e);
      }
    ).catch(
      error => {
        console.log('felse error', error);
      }
    );

    a(true).then(
      result => {
        console.log('true result', result);
      },
      e => {
        console.log('true e', e);
      }
    ).catch(
      error => {
        console.log('true error', error);
      }
    );

0 人点赞