简体   繁体   中英

How to return a specific value type in a promise using Angular/Typescript

I'm stuck on something that I think should be pretty simple. We have a child component that accepts an input as such:

@Input() accessories: { [key: string]: Accessory };

And when the component is initialzed the template is able to read and display the values but we also need them in the component but they're not available. So we're trying to use setTimeout to force a change:

setTimeout(() => {
  var resultArray = this.accessories;

  if (this.accessories!= undefined) {
        accessories.forEach(x =>
            Object.keys(this.accessories).findIndex(key => {
                if (this.accessories[key].accessoryId == x.accessoryId && this.accessories [key].code == "RECORD") {
                    this.isRecord= true;
                }
            }))}}, 2000);

But it still fires after we need it. I'm trying to implement a promise, which I haven't used before, so looking for some guidance on how to get this variable when it's available. I'm trying to wait for the result before continuing with the process.

You can construct a Promise like this:

function foo() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const returnValue = 'foo';
      resolve(returnValue);
    }, 2000);
  });
}

function main() {
  foo().then(res => console.log(res)); // 'foo'
}

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