Skip to content

Using for-await-of should resolve the Promise? #21115

Closed
@luthfianto

Description

@luthfianto

TypeScript Version:

  • typescript@2.6.2
  • typescript@2.7.0-dev.20180110

Code

declare function require(name:string);

(<any> Symbol).asyncIterator = Symbol.asyncIterator || Symbol.for("Symbol.asyncIterator");

const fetchlike = function(url) {
  // return new pending promise
  return new Promise((resolve, reject) => {
    // select http or https module, depending on reqested url
    const lib = url.startsWith('https') ? require('https') : require('http');
    const request = lib.get(url, (response) => {
      // handle http errors
      if (response.statusCode < 200 || response.statusCode > 299) {
         reject(new Error('Failed to load page, status code: ' + response.statusCode));
       }
      // temporary data holder
      const body = [];
      // on every content chunk, push it to the data array
      response.on('data', (chunk) => body.push(chunk));
      // we are done, resolve promise with those joined chunks
      response.on('end', () => resolve(body.join('')));
    });
    // handle connection errors of the request
    request.on('error', (err) => reject(err))
    })
};

async function example() {
  const arrayOfFetchPromises = [
    fetchlike('http://example.com'),
    fetchlike('http://example.com'),
  ];

  // Regular iterator:
  for (const item of arrayOfFetchPromises) {
    console.log(item); // Logs a promise
  }

  // for-await-of iterator:  
  for await (const item of arrayOfFetchPromises) {
    console.log(item); // Logs a response
  }
}

example()

tsc --lib es2017,esnext.asynciterable,dom Untitled-1.ts && node Untitled-1.js

Actual behavior:

item is a Promise in the for-await-of iterator block

imgur

Doing this causes error:

  for await (const item of arrayOfFetchPromises) {
    console.log(item.length); // TS error
  }
  for await (const item of arrayOfFetchPromises) {
    console.log((item as any).length);
    // not error because typecasted to any, logs valid result
  }

Expected behavior:

In the for-await-of iterator block,item should not be a Promise, because it's the actual value instead of a Promise

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions