javascript - Regarding Promise, why can't I get the correct execution order when I write it like this?
学习ing
学习ing 2017-07-05 11:02:27
0
1
825
$.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()
        });
}

Through ajax and then calling f2(), you can execute pullUpAction(news) first and then execute loaded(). But if f2() is executed directly, like the following:

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

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

The effect of Promise executing methods one after another cannot be achieved. Why is this?

学习ing
学习ing

reply all(1)
阿神
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)
        }

The result is

When there is no setting, the test1 function is executed first and then the promise object is returned successfully. A possible guess is that when you use an ajax request, the completion time of the f2 function is exactly the same as or less than the end time of the ajax request. , so you see the execution result you want, but when calling directly without ajax, the real response time is reflected. It is recommended to debug pullUpAction here. The above is my humble opinion and is for reference only.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template