首頁  >  問答  >  主體

javascript - 關於Promise,為何我這樣寫不能得到正確的執行順序?

$.ajax({
    url: '/latestNewsIndex',
    type: 'get',
    dataType: 'json',
    timeout: 1000,
    success: function (data, status) {
        if (data.value.length == 0) {
            alert("暂时没有更多新闻!");
        }
        else {
            f2(data.value);
        }
    },
    fail: function (err, status) {
        alert('暂时没有更多新闻!');
    }
})

function f2(news) {
    var promise = new Promise(function(resolve,reject) {
        pullUpAction(news);
        resolve(1);
    });

    promise.then(
        function(id) {
            loaded()
        });
}

透過ajax,然後呼叫f2(),可以實作先執行pullUpAction(news),結束後再執行loaded()。可是如果直接執行否f2(),像下面:

f2(news);
function f2(news) {
    var promise = new Promise(function(resolve,reject) {
        pullUpAction(news);
        resolve(1);
    });

    promise.then(
        function(id) {
            loaded()
        });
}

就無法達到Promise先後執行方法的效果,這是為什麼呢?

学习ing学习ing2663 天前793

全部回覆(1)我來回復

  • 阿神

    阿神2017-07-05 11:04:27

    test('test')
            function test (value) {
              let promise = new Promise(function (resolve, reject) {
                test1(value)
                resolve(1)
              })
              promise.then(function (id) {
                console.log('我后执行,我的值为:' + id)
              })
            }
    
            function test1 (value) {
              console.log(value)
              window.setTimeout(function (value) {
                console.log('我先执行,我的值为:' + value)
              }, 10 * 1000)
            }

    結果是

    在沒有設定時的時候是先執行的test1函數再執行promise物件成功時的返回.有可能的猜測就是你在使用ajax請求時,f2函數完成的時間剛好與ajax請求結束的時間一樣或者小於,所以你看到了你想要的執行結果,但是直接呼叫不通過ajax時則反應出了真實的反應時間。建議在這裡pullUpAction調試看看
    以上為本人愚見,僅做參考

    回覆
    0
  • 取消回覆