【问题标题】:Run a non promise function in the middle of promise then然后在 promise 中间运行一个非 promise 函数
【发布时间】:2020-06-05 20:45:30
【问题描述】:

我有三个基于 Promise 的函数,但我需要在中间运行一个非 Promise 函数。 例如:

function getListItems(listTitle) {
    var deferred = $.Deferred();
    var ctx = SP.ClientContext.get_current();
    var list = ctx.get_web().get_lists().getByTitle(listTitle);
    var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
    ctx.load(items);
    ctx.executeQueryAsync(
        function () {
            deferred.resolve(items);
        },
        function (sender, args) {
            deferred.reject(sender, args);
        }
    );
    return deferred.promise();
}

function prepareSchemaData(items) {
    //promise
}

function someNonPromiseFunc() {
    //returns some Object
}

function updateListItems(items) {
    //updates items using data from the object returned by someNonPromiseFunc
    //promise
}

getListItems('aList')
    .then(prepareSchemaData)
    .then(someNonPromiseFunc)
    .then(updateListItems);

显然,我不能像那样调用非承诺函数,但我需要确保在updateListItems 可以运行之前,someNonPromiseFunc 可以构建它的对象并完全返回。

【问题讨论】:

  • "显然,我不能像那样调用非承诺函数" - 是什么让你这么认为?
  • 你也可以写getListItems('aList').then(prepareSchemaData).then(data => updateListItems(someNonPromiseFunc(data)));

标签: javascript jquery asynchronous promise


【解决方案1】:

你可以用这个:

getListItems('aList')
    .then(prepareSchemaData)
    .then(someNonPromiseFunc)       // synchronous functions are allowed here
    .then(updateListItems);

你如何拥有它。您的同步非承诺函数将作为单个参数(它可以使用或不使用)传递前一个 .then() 处理程序的解析值。并且下一个.then() 处理程序将传递此同步函数的返回结果。这样就可以了。

.then() 处理程序可以返回普通值或解析为值的承诺。要么会工作。

因此,您可以使用同步代码作为.then() 处理程序就好了。因为它是同步的,所以下一个 .then() 处理程序在这个处理程序返回之前不会被调用。

对于这种情况,不需要像其他人建议的那样将同步函数包装在 Promise.resolve() 中。那只是不必要的代码。

【讨论】:

  • 谢谢,我显然需要重新访问 jQuery Promise 文档以更好地重新教育自己!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 2017-11-16
  • 2022-01-20
  • 2023-03-09
  • 2019-09-18
  • 1970-01-01
相关资源
最近更新 更多