ES6 Promise objects then chained method calls

The then action () method is to add solution (Fulfillment) and rejected (rejection) Promise instance callback status.

then () method returns a new of Promise instance, so then () method behind the chain can continue with another call then () method.

let p = new Promise((resolve, reject) => {
    setTimeout(resolve, 1000, 'success');
});
p.then(
    res => {
        console.log(res);
        return `${res} again`;
    }
)
    .then(
        res => console.log(res)
    );
// 连续
// success
// success again

But before a then () method in the callback function in turn may return a Promise instance, this time behind a then state before a Promise instance () method calls the callback function will wait until a change.

let p = new Promise((resolve, reject) => {
    setTimeout(resolve, 1000, 'success');
});
p.then(
    res => {
        console.log(res);
        return new Promise((resolve, reject) => {
            setTimeout(resolve, 1000, 'success');
        });
    }
)
    .then(
        res => console.log(res)
    );
// 相隔1000ms
// success
// success

Guess you like

Origin www.cnblogs.com/qdlhj/p/12067821.html