Understanding Promises by Example

Based on ES6 syntax.

Create Promises

// 能正常完成的例子,任务成功做完是调用 resolve,参数是一个字符串消息
let promiseOK = new Promise(
    (resolve, reject) => {
        // 这里是任务逻辑
        resolve("成功完成");
    }
);

// 不能正常完成的例子,任务失败,调用 reject, 参数是一个字符串消息
let promiseReject = new Promise(
    (resolve, reject) => {
        // 这里是任务逻辑
        reject("无法完成");
    }
);

// 任务执行过程中遇到异常的例子,没有调用 resolve, 也没有调用 reject, 
// 只是使用 throw 抛出错误消息
let promiseException = new Promise(
    (resolve, reject) => {
        // 这里是任务逻辑
        throw("异常");
    }
);

Run the Promise and handle it depending on the outcome

The result of the run was successful – resolve was called

promiseOK.then((data) => {
    console.log("OK:" + data)
}).catch((data) => {
    console.log("ERROR:" + data)
})

The output of the above example is:

OK: successfully completed

chain twice then

// 会输出 : 
// THEN1:成功完成
// THEN2:undefined
promiseOK.then((data) => console.log("THEN1:" + data))
         .then((data) => console.log("THEN2:" + data))

Rejected during runtime - reject was called

promiseReject.then((data) => {
    console.log("OK:" + data)
}).catch((data) => {
    console.log("ERROR:" + data)
})

The output of the above example is:

ERROR: could not complete

chain double catch

// 会输出 : 
// ERROR1:无法完成
promiseReject.catch((data) => console.log("ERROR1:" + data))
             .catch((data) => console.log("ERROR2:" + data))

An exception was encountered during operation - throw was used

promiseException.then((data) => {
    console.log("OK:" + data)
}).catch((data) => {
    console.log("ERROR:" + data)
})

The output of the above example is:

ERROR: exception

chain double catch

// 会输出 : 
// ERROR1:异常
promiseException.catch((data) => console.log("ERROR1:" + data))
                .catch((data) => console.log("ERROR2:" + data))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325591265&siteId=291194637