简体   繁体   中英

How to use postMessage with the result of a promise in JS

I am trying to pass an object back to the Renderer using postMessage().

The code resolves fine and creates my object after a series of fetches.

loadMainTbls()
.then(retVal => buildMainTbl(retVal))
.then(dat => reduceMainTbl(dat))
.then(res => postMessage(res))

If I console.log(res) the proper Array is logged out. I realize that res is a promise.

.then(res => postMessage(new Promise(function(resolve) {
    resolve(res)
})))

When I try to resolve res, it always comes back as an array with length of zero. On some attempts, I received a # Could not be cloned error.

I've tried to visualize what I could be doing wrong with no success. Could someone help me to be able to take the promisevalue and post Message it back to the renderer.

The definitive answer is that, I didn't have a thorough understanding of the concept of Promises. After researching and shifting my mind from a synchronous line after line execution mode into a create promise, resolve promise, .then() mindset. I was able to solve this question and several others.

I was trying to assign values outside of the scope and execution of the promise -.then() flow. I learned that If I'm trying to compute something with a promise. I can do whatever I want at the end of the promise chain. That the promise chain only executes Promise -> resolve ->.then() or.catch(). Sorry community, This is 101 stuff, but I learned and understood a very important principle. Fetch save much time over XHR calls even async XHR calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM