Assign resolve function from Promise to a variable

孤人 提交于 2021-01-29 10:06:55

问题


There's a snippet of code that I cannot seem to understand. There's a function that is declare empty at first:

let dCredentials = (credentials: any) => {}

Then this variable is later reasignned in a function later called:

  return new Promise((resolve, _) => (dispatchCredentials = resolve))

What does the second code do? Does it return anything after someone uses .then in the promise?


回答1:


If you get a reference to the resolve function to outside the promise, then you can resolve it at any point manually with any value you want.

A simplistic example:

//create a variable to use for the resolve function
let outsideResolve;

//make a promise
const p = new Promise((resolve) => outsideResolve = resolve);

//attach callbacks
p
  .then(value => value.toUpperCase())
  .then(value => value + "!")
  .then(value => console.log("Final value:", value));

//add a click listener that will be invoked at any point in time
document.getElementById("click_me").addEventListener("click", () => {
  const input = document.getElementById("fill_me");
  
  //resolve the promise once clicked
  outsideResolve(input.value);
})
<input type="text" id="fill_me"/>

<button id="click_me">resolve with value</button>

You can still use the Promise as normal but you have more control over when and how it's resolved.

This can be helpful if you know what operations you want to do but cannot say when they need to be applied as the data (and thus resolution) will come later.

In addition, you might have to add more and more .then calls indeterminably until some condition causes the promise to resolve. Try entering "hello" -> add to sentence -> enter "world" -> add to sentence -> build sentence

//create a variable to use for the resolve function
let outsideResolve;

//make a promise
let p = new Promise((resolve) => outsideResolve = resolve);

//add a click listener that will be invoked at any point in time
document.getElementById("add_me").addEventListener("click", () => {
  const input = document.getElementById("fill_me");
  
  const inputValue = document.getElementById("fill_me").value;
  
  p = p.then(value => `${value} ${inputValue}`);
  console.log(`"${inputValue}" added.`)
  
  input.value = "";
})

//add a click listener that will be invoked at any point in time
document.getElementById("click_me").addEventListener("click", () => {
  //attach final callbacks
  p
    .then(value => value.toUpperCase())
    .then(value => value + "!")
    .then(value => console.log("Final value:", value));

  //resolve the promise once clicked
  outsideResolve("start resolving");
})
<input type="text" id="fill_me"/>

<button id="add_me">add to sentence</button>
<button id="click_me">build sentence</button>


来源:https://stackoverflow.com/questions/59776151/assign-resolve-function-from-promise-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!