我有多个小部件页面。小部件的内容是静态的,但它们的显示可以改变。我需要能够存储这些,所以我正在构建一个多维对象。
我需要存储对象并显示对象。
这是我工厂的简化版本:
const createWidget = ({
id = undefined,
name = 'new widget',
style = 'vertical_list',
html = undefined,
} = {}) => ({
id,
name,
style,
data,
constructWidget () {
return $.ajax({
url: '/my/url',
type: 'POST',
data: {
'_token' : window.xsrf_token,
'widget_id': this.id,
},
dataType: 'json',
}).then(reponse => {
let widget = response.widget;
this.name = widget.name;
this.style = widget.style;
this.html = widget.html;
});
},
})
用一切都很好地保湿物体,但是我无法将物体弄回来。
let book = {};
let page = 'example page';
book[page] = book[page] || {};
let widget_id = 88;
// TRYING TO STORE
// this just give me the promise and I can't get at the object :(
book[page][widget_id] = CreateWidget({id: widget_id}).constructWidget();
// TRYING TO DISPLAY
let widget = book[page][widget_id];
$(`#current_page`).append(`
<div id="widget_${widget.id}" class="${style}">
<b>${widget.name}</b>
${widget.html}
</div>`
);
所以?为什么这种做法很愚蠢,我该如何解决?我已经尝试过搞乱一堆承诺了,但是如果没有水合物的话,我似乎无法做一件好事。
答案 0 :(得分:0)
你需要以某种方式等待这些承诺
最简单(嗯,至少是更短的代码示例)方式是使用async / await
async function() {
book[page][widget_id] = await CreateWidget_1({id: widget_id}) //the promise :(
book[page][widget_id] = await CreateWidget_2({id: widget_id}) //maybe...
$(`#current_page`).append(`<div>${book[page][widget_id]}</div>`); //nope, that'll be undefined because the promise isn't complete this isn't an asynch approach, dummy
或更长的承诺
Promise.all[CreateWidget_1(...), CreateWidget_2(...)])
.then(function() { $(`#current_page`).append(...) })
此外,链接是最重要的承诺概念之一,要正确使用承诺,它们需要返回,你的函数都需要返回承诺(只有一个返回它)
答案 1 :(得分:0)
问题是我需要返回this
作为承诺的一部分。我没有这样做。非常感谢@JaromandaX。
返回promise和对象意味着我继续在异步路径上。简化示例答案如下。
const createWidget = ({
id = undefined,
name = 'new widget',
style = 'vertical_list',
html = undefined,
} = {}) => ({
id,
name,
style,
data,
constructWidget () {
return $.ajax({
url : '/my/url',
type: 'POST',
data: {
'_token' : window.xsrf_token,
'widget_id': this.id,
},
dataType: 'json',
}).then(reponse => {
let widget = response.widget;
this.name = widget.name;
this.style = widget.style;
this.html = widget.html;
return this; // <-- here's what I was missing.
});
},
})
let book = {};
let page = 'example page';
book[page] = book[page] || {};
let widget_id = 88;
CreateWidget({id: widget_id})
.constructWidget()
.then(widget => {
book[page][widget_id] = widget;
$(`#current_page`).append(`
<div id="widget_${widget.id}" class="${style}">
<b>${widget.name}</b>
${widget.html}
</div>`
);
})
.fail(error => console.error);
关于文章说a then
内部的回归毫无意义!