bluebird -1 New Promise方法

时间:2023-03-09 19:13:17
bluebird -1 New Promise方法

new Promise(function(function resolve, function reject) resolver) -> Promise

创建一个Promise,传一个函数参数 resolve和reject,两个函数用来决定返回值或者报出异常

例子1:

function ajaxGetAsync(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest;
xhr.addEventListener("error", reject);
xhr.addEventListener("load", resolve);
xhr.open("GET", url);
xhr.send(null);
});
}

例子2:

new Promise(function (resolve, reject) {

    reject('hehe')

}).then(function (val) {

    return 2

}).then(function (val) {

    console.log(val)

    return 3

}).then(function (val) {

    console.log(val)

}).catch(function (e) {

  console.log(e)

}) //输出”hehe”

例子3:

new Promise(function (resolve, reject) {

    //这里会线性执行

    for(var i = 0; i < 10; i++) {

        console.log(i)

    }

    resolve(1)

}).then(function (val) {

    return 2

}).then(function (val) {

    console.log(val)

    return 3

}).then(function (val) {

    console.log(val)

}).catch(function (e) {

  console.log(e)

})

总结:new Promise,把要顺序执行的操作放在函数体内,要想返回最后值,调用resolve(data),之后用then(function(data){  })接收。 要想返回错误,则reject(“错误对象”),之后用catch补获。

相关文章