Javascript promise 深入堆栈

标签 javascript promise

我决定在创建模型时对服务器进行回退调用,以防我们无法从本地可用信息中找到值。如果可能的话,我想让它异步,这是否意味着我必须让这个代码链中的所有内容消耗并返回 promise ?

我将首先使用伪代码来说明这一点,因为调用堆栈可能有点长,因此我们不会包含与此问题无关的内容。如果您需要更多内容,请告诉我。

function router() {
    if (condition) {
        controller.renderDocument(options);
    }
}

controller.renderDocument(options) {
    documentCollection.findOrCreateDocumentHolder(options);
}

documentCollection.findOrCreateDocumentHolder(options) {
    var model = this.findOrCreateDocument(options);
}

documentCollection.otherFunction(options) {
    // just to illustrate that there's several entry points to this kind of functionality
    var model = this.findOrCreateDocument(options);
}

documentCollection.findOrCreateDocument(options) {
    if (!options.type)
        options.type = resolveType(options);
    // other things that use the found options.type
    return model;
}

resolveType(options) {
    var locallyResolved = resolveLocally(options);
    if (locallyResolved)
        return locallyResolved;
    // try the server as a fallback
    var serverResolved = resolveFromServer(options.id);
    return serverResolved;
}

resolveLocally(options) {
    return stuff;
}

resolveFromServer(id) {
    return ajaxRequestResult();
}

显然,实际的代码有点长,而且确实做了一些事情。

为了 1 个可能的 ajax 请求而使用所有这些链接 promise 感觉有点过分,特别是因为这种情况很少发生。另一种选择是仅发出同步 AJAX 请求。

我唯一的选择是让一切都使用 Promise 和 Whens,还是使其成为同步 AJAX 请求?有更好的选择吗?我正在考虑 C# 的 wait 关键字,但我确信其他语言也有类似的功能。

最佳答案

I want to have it async if possible, does it mean I have to make everything in this chain of code consume and return promises?

是的。潜在异步的东西必须始终返回一个 promise ,并且必须始终像异步一样使用(无论如何 promise 都会强制执行此操作)。

Is the only other alternative to just make a synchronous AJAX request?

是的,你真的不希望这样。

Is there a nicer alternative? I'm thinking of C#'s await keyword, but I'm sure other languages have similar functionality.

事实上,async-await is coming to ECMAScript以及。但它并不使任何东西同步,它只是无处不在的 Promise 的语法糖。

关于Javascript promise 深入堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31072272/

相关文章:

javascript - 使带有回调/ promise 实现的 javascript 函数始终返回 promise

javascript - 如何从 Controller 的函数为范围变量赋值

javascript - 使用异步 while 循环创建和插入文档

javascript - 预先输入下拉列表中的全局页脚

javascript - 在 JavaScript 中反转整数

javascript - 为什么我的函数返回与 Chrome 浏览器中的 console.log() 不同

javascript - 为什么我无法打印重叠矩形的 id?

javascript - 带有下划线和最小出现次数且没有最大出现次数的字母数字字符串模式的正则表达式 - javascript

javascript - 我该如何解决这个 promise ,这样我就不会发回未定义的内容

javascript - promise API