之前看过几次关于Promise的文档,但是一直没有实际用过,今天在写一个函数的时候,遇到了执行顺序的问题,大概就是,执行一个函数,里面step1是一个异步的api,下面step2要用到step1处理过的数据,然后一直不成功,打印了一下,看到step2先于step1执行了,就是这样:
function funcName(){
step1;
step2
}
console.log结果是
step2
step1
因为step2要用到step1处理的数据,但是step2先于step1执行了,所以函数执行达不到目标效果。想到了Promise,于是试了一下
function funcName(){
new Promise((resolve,reject)=>{
step1(){
//xxx
success: function (res) {
resolve(res.data);
},
fail(err) {
reject(err)
}
};
}).then(res=>{
console.log(res)
step2直接在这里处理step1传下来的res
})