2017-03-07 127 views
0

为了在别人可以处理这些数据之前转换某些数据,我必须在函数内部执行一个Fetch promise return。 所以我创造了这个代码(只是简单展现的想法):函数承诺执行的顺序

function test() { 

    return new Promise(function (resolve, reject) { 
    // Fetch('www.google.com') 
    setTimeout(resolve, 1000); 
    }).then(function() { 
    // convert data, etc 
    console.log(1); 
    }); 
} 
// after conversion, handle it to someone else 
test().then(console.log(2)); 

运行它,我认为控制台将显示:1 2,但不断出现2 1.有没有其他办法可以做到这一点?

+0

您需要传递'.then()'a * function *。 'test()。then(function(){console.log(2)});' –

回答

1

就像你与console.log(1)一样,你需要将它传递给then作为回调之前包裹在一个函数的第二个电话。

test().then(function() { 
    console.log(2); 
}); 

然后,它会显示12预期。

+0

非常感谢,疯狂的细节... – MarcosCunhaLima