javascript - Javascript 中的 promise

标签 javascript promise

我一直在查看有关如何使用 promises 的各种讨论,但我没有得到任何工作。

我一直收到错误消息“无法读取未定义的属性。”

“然后”、“完成”等是 Javascript 内置的吗?或者他们是否要求我包含一些其他外部脚本?

这是我最近尝试用 2 个简单的对话框进行实验(确认和拒绝都是简单的对话框):

var confirmWithPromise = Confirm(); 
var reject = confirmWithPromise.then(Reject("This record cannot be deleted."));

如果我能以最简单的方式开始让我的示例正常工作,我想我可以从那里开始。

谢谢。

更新:这是我的 Confirm() - 它没有返回 promise 。我不完全明白如何实现它的返回:

 function Confirm() {
    var buttons = [
{
    text: "Yes",
    //icons: {
    //    primary: "ui-icon-heart"
    //},
    click: function () {
        $(this).dialog("close");
        callback(true);
    }

    // Uncommenting the following line would hide the text,
    // resulting in the label being used as a tooltip
    //showText: false
},
{
    text: "No",
    //icons: {
    //    primary: "ui-icon-heart"
    //},
    click: function () {
        $(this).dialog("close");
        callback(false);
    }

    // Uncommenting the following line would hide the text,
    // resulting in the label being used as a tooltip
    //showText: false
}
    ];

    showDialog("Confirm", "Are you sure?  Once the record is deleted, it cannot be recovered.", buttons);

}

最佳答案

Is the "then," "done," etc. built-in to Javascript?

是的。它们是 Promise objects 的方法由 the ES6 specification 定义.

I keep getting an error "Cannot read property then of undefined."

您只能在 promise 对象上使用它们。该错误消息表明 Confirm 的返回值(这不是 JavaScript 内置的,尽管 confirm (c 不是C) 由浏览器作为 Web API 提供)是 undefined 而不是 promise 对象。

您需要编辑 Confirm 以便它返回 promise 。

关于javascript - Javascript 中的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37550683/

相关文章:

javascript - 解析[错误] : success/error was not called (Code: 141, 版本 : 1. 9.0)

javascript - Jquery 错误地按 id 对 <li> 进行排序

javascript - 从另一个函数内部调用日期选择器选项函数

javascript - ReactNative native-modules Promise 传递字段和 Swift

javascript - Ng-Repeat 中的 Angular 设置类

javascript - 正则表达式 - 如何匹配整个字符串并仅捕获具有一定长度的子组

javascript - 如何为文本中的元素分配唯一的点击事件?

javascript - 我对 new Promise((resolve, reject) => {[loop]}) 阻塞而 Promise.resolve().then([loop]) 不是阻塞感到困惑

javascript - `Q.when` 的 Bluebird 等价物是什么?

node.js - 如何将对象或变量与 Promise.all 一起传递?